package com.ludomancy.gamelib;

import java.applet.Applet;
import java.awt.Image;
import java.awt.MediaTracker;


public class GameApplet extends Applet implements ImageLoader, Runnable
{
	public GameCanvas gameCanvas = null;
	int frame;
    int delay;
    Thread thread;
	
	public void init()
	{
		// init res manager
		ResourceManager.init(this, "/");
		// init game canvas
		gameCanvas = new GameCanvas(new Theme());
		gameCanvas.setSize(getSize());
		add(gameCanvas);
		doLayout();
		int fps = 20;
		delay = (fps > 0) ? (1000 / fps) : 100;
	}
	
    public void start() 
    {
    	thread = new Thread(this);
    	thread.start();
	}

	public void run()
	{
		// Remember the starting time
		long tm = System.currentTimeMillis();
		while (Thread.currentThread() == thread)
		{
			// Display the next frame of animation.
			gameCanvas.run();

			// Delay depending on how far we are behind.
			try
			{
				tm += delay;
				Thread.sleep(Math.max(0, tm - System.currentTimeMillis()));
			} 
			catch (InterruptedException e)
			{
				break;
			}

			// Advance the frame
			frame++;
		}
	}

	public void exit()
	{
		thread = null;
	}
	
	public Image loadImage(String file)
    {
        Image img = getImage(getClass().getResource(file));
        MediaTracker m = new MediaTracker(this);
        m.addImage( img, 1 );
        try
        {
        	m.waitForAll();
        }
        catch( InterruptedException e )
        {
        }
        return img;
    }
}
